package com.im.dynamic.controller;

import com.alibaba.fastjson.JSON;
import com.im.common.utils.R;
import com.im.dynamic.entity.Album;
import com.im.dynamic.service.AlbumService;
import com.im.dynamic.service.UserService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * User: key
 * ClassName:PublishController
 * Date: 2023/7/13
 * Time: 11:40
 * description:
 */
@RestController
public class PublishController {

    @Autowired
    private UploadManager uploadManager;


    @Value("${spring.qiniuyun.ak}")
    private String ak;

    @Value("${spring.qiniuyun.sk}")
    private String sk;

    @Value("${spring.qiniuyun.bucket}")
    private String bucket;

    @Value("${spring.qiniuyun.host}")
    private String host;

    @Autowired
    private UserService userService;

    @Autowired
    private AlbumService albumService;


    /**
     * 动态相片上传
     */
    @RequestMapping("/file/upload")
    public R upload(MultipartFile file, Integer id) {

        // 1、文件名称
        String key = file.getOriginalFilename();

        // 2.认证
        Auth auth = Auth.create(ak, sk);

        // 3.获取token
        String upToken = auth.uploadToken(bucket, key);

        // 4.上传
        String path = null;

        Album album = new Album();

        album.setUId(id);

        album.setPath(file.getOriginalFilename());

        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            path = host + defaultPutRet.key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 写入数据库
        albumService.save(album);

        return R.seccess("成功");
    }

    @GetMapping("/publish/qiniu/token")
    public R token(){
        return R.seccess();
    }

}
